//
//  CWQ_DownloadVC.m
//  BaxTer
//
//  Created by 陈武琦 on 16/9/1.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "CWQ_MessageVC.h"
#import "CWQ_messageCell.h"
#import "BTCollectionBottomMenuView.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "CWQ_tableView.h"
#import "BTBaseWebVC.h"
#import "BTCourseDetailVC.h"
#import "BTTopicDetailVC.h"
#import "Masonry.h"

static NSString * const cellId = @"CWQ_messageCellID";

@interface CWQ_MessageVC ()<BTCollectionBottomMenuViewViewDelegate>

@property(nonatomic, strong)CWQ_tableView *tableView;
//上拉加载的页面
@property (nonatomic, assign) NSInteger page;


@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)BTCollectionBottomMenuView *bottomMenu;
@property (nonatomic, copy) NSMutableDictionary *deleteDic;

@end

@implementation CWQ_MessageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"通知";
    [self setupSubviews];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)setupSubviews {
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[CWQ_tableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain cellClass:@"CWQ_messageCell" vc:self upload:YES];
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    _dataSource = [NSMutableArray array];
    _page = 1;
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [_tableView cwq_requestDataWithDown:YES];
    

    UIButton *rightItemBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightItemBtn setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
    [rightItemBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    rightItemBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [rightItemBtn addTarget:self action:@selector(deleteClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:rightItemBtn]];
    defineWeakSelf;
    [self.bottomMenu mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(kScreenWidth+2, 44));
        make.left.equalTo(weakSelf.view).with.offset(0);
        make.top.equalTo(weakSelf.tableView.mas_bottom).with.offset(0);
        
    }];

}

- (void)deleteClick:(UIButton *)btn {
    self.tableView.editing = !self.tableView.editing;
    if (self.tableView.editing) {
        [btn setImage:nil forState:UIControlStateNormal];
        [btn setTitle:@"取消" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 44, 0));
        }];
    }else {
        
        [btn setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
        [btn setTitle:@"" forState:UIControlStateNormal];
        [self.deleteDic removeAllObjects];
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }
}


- (void)cwq_tableView:(CWQ_tableView *)tableView requestDataWithDown:(BOOL)down {
    
    if (down) {
        self.page = 1;
    }else {
        self.page ++;
    }

   
    tableView.loading = YES;
    int count = 10;
    NSDictionary *param = @{@"page":@(self.page), @"rows":@(count)};
    defineWeakSelf;
    [[BTNetworkManager sharedMg] POST:BTNotifiListUrl parameters:param success:^(id responseObject) {
         [tableView.header endRefreshing];
          [tableView.footer endRefreshing];
         tableView.loading = NO;
        if (responseObject_success) {
            NSArray *arr = [CWQ_messageM mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]];
            //判断是上拉刷新？  还是下拉加载？
            if (!down) {
                NSMutableArray *muArr = [weakSelf.dataSource mutableCopy];
                
                [muArr addObjectsFromArray:arr];
                weakSelf.dataSource = muArr;
                if (![responseObject[@"data"][@"totalPage"] isKindOfClass:[NSNull class]] && weakSelf.page == [responseObject[@"data"][@"totalPage"] integerValue]) {
                    tableView.footer.hidden = YES;
                }
              
            }else {
              
                if ( ![responseObject[@"data"][@"totalPage"] isKindOfClass:[NSNull class]] && weakSelf.page == [responseObject[@"data"][@"totalPage"] integerValue]) {
                    tableView.footer.hidden = YES;
                }else {
                    tableView.footer.hidden = NO;
                }
                self.dataSource = [arr mutableCopy];
               
            }
           
            
           
        }
    } failure:^(NSString *err) {
           [tableView.footer endRefreshing];
           [tableView.header endRefreshing];
        if (weakSelf.page > 1) {
            //上拉
        
            weakSelf.page -= 1;
        }else {
            //下拉
        
            if (self.dataSource.count<=0) {
                tableView.footer.hidden = YES;
            }else {
                
                tableView.footer.hidden = NO;
            }
        }
        cwqHudRequestError(err);
        if (self.dataSource.count<=0) {
            tableView.loading = NO;
        }
        
    }];
}

- (void)setDataSource:(NSMutableArray *)dataSource {
    _dataSource = dataSource;
    [self.tableView setupSourceArray:dataSource];
}

- (NSMutableDictionary *)deleteDic {
    
    if (!_deleteDic) {
        _deleteDic = [@{} mutableCopy];
    }
    
    return _deleteDic;
}

- (BTCollectionBottomMenuView *)bottomMenu {
    if (!_bottomMenu) {
        _bottomMenu = [BTCollectionBottomMenuView menuView];
        _bottomMenu.delegate = self;
        [self.view addSubview:_bottomMenu];
    }
    
    return _bottomMenu;
    
}
#pragma mark ----------------tableview代理--------------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CWQ_messageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    //设置cell 的分割线
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    [cell setModel:self.dataSource[indexPath.row]];
    
      return cell;
    
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    
    CWQ_messageM *model = [self.dataSource objectAtIndex:indexPath.row];
    if (tableView.editing) {
       
        [self.deleteDic setObject:model forKey:model.pushId];
        [self resetDeleteBtnTitle];
        return;
    }
    
    if ([model.isRead integerValue] <=0) {
        [self remarkNotiToServerWithModel:model];
    }
    
//    QUESTIONNAIRE  问卷推送
//    CURRICULUM  课程推送
//    SPECIAL 专题推送
//    
//    INFORMATION 资讯推送
    NSString *type = model.notifType;
    if ([type isEqualToString:@"QUESTIONNAIRE"]) {
        BTBaseWebVC *vc =[BTBaseWebVC new];
       NSString * typeStr = kQuestionDetai;
       NSString * url = [NSString stringWithFormat:@"%@/%@/%@",[BTNetworkManager sharedMg].bathURL,typeStr,model.sourceId];
        vc.url =url;
        [self.navigationController pushViewController:vc animated:YES];

        
    }else if([type isEqualToString:@"CURRICULUM"]){
        BTCourseDetailVC *vc =[BTCourseDetailVC new];
        vc.courseId = [model.sourceId integerValue];
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        [self.navigationController pushViewController:vc animated:YES];
    
    }
     else if([type isEqualToString:@"SPECIAL"]){
         BTTopicDetailVC *vc =[BTTopicDetailVC new];
         vc.topicId = [model.sourceId integerValue];
         [self.navigationController setNavigationBarHidden:YES animated:YES];
         [self.navigationController pushViewController:vc animated:YES];
     
     }
     else if([type isEqualToString:@"INFORMATION"]){
         BTBaseWebVC *vc =[BTBaseWebVC new];
         NSString *typeStr = nil;
         NSString *url;
         typeStr = kConsultDetail;
         url = [NSString stringWithFormat:@"%@/%@/%@",[BTNetworkManager sharedMg].bathURL,typeStr,model.sourceId];
         vc.url =url;
         vc.tagKey  =  @"consult";
         [self.navigationController pushViewController:vc animated:YES];
    
     }
   
   
    
}


- (void)remarkNotiToServerWithModel:(CWQ_messageM *)model{
   
    weakSelf_define;

    NSString *url = [NSString stringWithFormat:@"%@/%@",kRemarkNotiStateus,model.pushId];
    [[BTNetworkManager sharedMg] GET:url parameters:nil success:^(id responseObject) {
        if (responseObject_success) {
            model.isRead = [@(1) stringValue];
            [weakSelf.tableView reloadRowsAtIndexPaths: @[[NSIndexPath indexPathForRow:[self.dataArray indexOfObject:model] inSection:0]] withRowAnimation:0];
        }
    } failure:^(NSString *err) {
        
    }];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.editing) {
        CWQ_messageM *model = [self.dataSource objectAtIndex:indexPath.row];
        [self.deleteDic removeObjectForKey:model.pushId];
        [self resetDeleteBtnTitle];
    }
}

- (void)resetDeleteBtnTitle {

    NSString *deleTitle;
    if ([self.deleteDic count] == 0) {
        deleTitle = @"删除";
    }else {
        
        deleTitle = [NSString stringWithFormat:@"删除(%zd)",[self.deleteDic count]];
    }
    [self.bottomMenu.deleteBtn setTitle:deleTitle forState:UIControlStateNormal];

}

#pragma mark ----------------bottomMenu代理--------------------------
- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickSelectBtn:(UIButton *)button {
    if ([button.titleLabel.text isEqualToString:@"全选"]) {
        [button setTitle:@"全不选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataSource.count; i++) {
            CWQ_messageM *model = [self.dataSource objectAtIndex:i];
            [self.deleteDic setObject:model forKey:model.pushId];
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES scrollPosition:NO];
            
        }
    }else {
        [button setTitle:@"全选" forState:UIControlStateNormal];
        for (int i = 0; i < self.dataSource.count; i++) {
            CWQ_messageM *model = [self.dataSource objectAtIndex:i];
            [self.deleteDic removeObjectForKey:model.pushId];
            [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES];
            
        }
    }
    [self resetDeleteBtnTitle];
}

- (void)cwqMenuView:(BTCollectionBottomMenuView *)menuView clickDeleteBtn:(UIButton *)button {
    
    if (self.deleteDic.count == 0) {
        return;
    }
   
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    cwqHud;
    params[@"ids"] =  [[self.deleteDic allKeys] componentsJoinedByString:@","];;
    weakSelf_define;
    [[BTNetworkManager sharedMg] POST:BTRemoveNotifiUrl parameters:params success:^(id responseObject) {
        if (responseObject_success) {
            cwqAlertMessage(@"删除成功");
            if ([weakSelf.deleteDic count] == self.dataSource.count) {
                [weakSelf.deleteDic removeAllObjects];
                NSMutableArray *muA = [NSMutableArray arrayWithArray:self.dataSource];
                [muA removeAllObjects];
                weakSelf.dataSource = [muA copy];
                [button setTitle:@"删除" forState:UIControlStateNormal];
                return;
            }
            
            NSMutableArray *muA = [self.dataSource mutableCopy];
            [muA removeObjectsInArray:[self.deleteDic allValues]];
            [weakSelf.deleteDic removeAllObjects];
            weakSelf.dataSource = [muA copy];
            [button setTitle:@"删除" forState:UIControlStateNormal];
//            [weakSelf.tableView cwq_requestDataWithDown:YES];
        }
    } failure:^(NSString *err) {
        
    }];
   
}


#pragma mark - 删除通知-------
- (void)deleteNoticesIds:(NSArray *)ids{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    cwqHud;
    params[@"ids"] =  [ids componentsJoinedByString:@","];;
    [[BTNetworkManager sharedMg] POST:BTRemoveNotifiUrl parameters:params success:^(id responseObject) {
        if ([responseObject[@"success"] boolValue]) {
            cwqAlertMessage(@"删除成功");
            [self.tableView cwq_requestDataWithDown:YES];
        }
    } failure:^(NSString *err) {

    }];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
